package com.wellsoft.mobileoa;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.wellsoft.mobileoa.dbmodel.ContactInfo;
import com.wellsoft.mobileoa.utils.BaseActivity;
import com.wellsoft.mobileoa.utils.SystemConfig;
import com.wellsoft.mobileoa.utils.action.SyncAddress;
import com.wellsoft.mobileoa.wsmodel.WSOA_Action;
import com.wellsoft.mobileoa.wsmodel.WSOA_Dept;
import com.wellsoft.mobileoa.wsmodel.WSOA_DownloadOpinion_Request;
import com.wellsoft.mobileoa.wsmodel.WSOA_DownloadOpinion_Response;
import com.wellsoft.mobileoa.wsmodel.WSOA_DownloadUnit_Request;
import com.wellsoft.mobileoa.wsmodel.WSOA_DownloadUnit_Response;
import com.wellsoft.mobileoa.wsmodel.WSOA_HttpGet_Request;
import com.wellsoft.mobileoa.wsmodel.WSOA_HttpGet_Response;
import com.wellsoft.mobileoa.wsmodel.WSOA_Login_Request;
import com.wellsoft.mobileoa.wsmodel.WSOA_Login_Response;
import com.wellsoft.mobileoa.wsmodel.WSOA_Role;
import com.wellsoft.mobileoa.wsmodel.WSOA_User;
import com.wmobile.utils.BaseObject;
import com.wmobile.utils.ServiceResponse;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class LoginActivity extends BaseActivity {
	LinearLayout fatherView;
	EditText usernameEt;
	EditText passwordEt;
	ImageButton loginIbn;
	ImageButton loginConfigIbn;
	ImageView coverIv;
	Boolean isExecuting = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loginact);
		init();
	}

	void init() {
		fatherView = (LinearLayout)findViewById(R.id.loginact_loginfatherll);
		fatherView.setOnClickListener(onBackGroundClicked);
		
		usernameEt = (EditText) findViewById(R.id.loginact_usernameet);
		passwordEt = (EditText) findViewById(R.id.loginact_passwordet);
		loginIbn = (ImageButton) findViewById(R.id.loginact_loginibn);
		loginConfigIbn = (ImageButton) findViewById(R.id.loginact_loginconfigibn);

		loginIbn.setOnClickListener(onLoginBtnClickListener);
		loginIbn.setOnTouchListener(onLoginTouchListener);

		loginConfigIbn.setOnClickListener(onLoginConfigBtnClickListener);
		SystemConfig.init(this);

		usernameEt.setText(SystemConfig.readRememberedUserName());
		passwordEt.setText(SystemConfig.readRememberedPassword());
	}

	OnClickListener onBackGroundClicked = new OnClickListener(){

		@Override
		public void onClick(View v) {
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
			imm.hideSoftInputFromWindow(v.getWindowToken(), 0); //强制隐藏键盘 
		}
		
	};

	OnClickListener onLoginConfigBtnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			LoginConfigPopDialog dialog = new LoginConfigPopDialog(
					LoginActivity.this);
			dialog.show();
		}
	};

	OnTouchListener onLoginTouchListener = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			ImageButton ib = (ImageButton) v;
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				ib.setBackgroundColor(Color.argb(127, 255, 255, 255));
			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				ib.setBackgroundColor(Color.argb(0, 255, 255, 255));
			} else if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
				ib.setBackgroundColor(Color.argb(0, 255, 255, 255));
			} else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
				ib.setBackgroundColor(Color.argb(0, 255, 255, 255));
			}
			return false;
		}
	};

	OnClickListener onLoginBtnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// WSOA_Action wsAction = new WSOA_Action();
			// wsAction.setFuncType("z(\"address\",\"down_url\",\"up_url\",\"up/down/updown/fullup/fulldown\")");
			// SyncAddress action = new SyncAddress(wsAction,
			// LoginActivity.this);
			// action.excuteAction();
			synchronized (LoginActivity.this.isExecuting) {
				if (isExecuting) {
					return;
				}
				isExecuting = true;
				Date date = new Date();
				try {
					if (date.after(SystemConfig.dateSdf.parse("2014-01-15"))) {
						isExecuting = false;
						return;
					}
				} catch (ParseException e) {
					e.printStackTrace();
					return;
				}
				String username = usernameEt.getText().toString().trim();
				String password = passwordEt.getText().toString();
				SystemConfig.getService().setWebserviceUrl(
						"http://" + SystemConfig.readServerUrl()
								+ "/wsoaservice/MobileOAService.asmx");

				if (SystemConfig.stringIsNullOrEmpty(username)) {
					isExecuting = false;
					LoginActivity.this.showMessage("请填入用户名！");
					return;
				}

				if (SystemConfig.stringIsNullOrEmpty(password)) {
					isExecuting = false;
					LoginActivity.this.showMessage("请填入密码！");
					return;
				}

				AlertDialog alertDialog = LoginActivity.this
						.showWaitingDialog();

				Map<String, BaseObject> requests = new HashMap<String, BaseObject>();

				WSOA_Login_Request login_Request = new WSOA_Login_Request();
				login_Request.setUsername(username);
				login_Request.setPassword(password);
				login_Request.setDeviceType("AND");
				login_Request.setDeviceToken(SystemConfig.getDeviceId());

				requests.put("request", login_Request);
				ServiceResponse response = SystemConfig.getService()
						.Callservice(requests, "WSOA_Login",
								WSOA_Login_Response.class);
				if (!response.getExeFlag()) {
					alertDialog.dismiss();
					isExecuting = false;
					LoginActivity.this.showMessage(response.getMessage());
					return;
				}
				WSOA_Login_Response login_response = (WSOA_Login_Response) response
						.getResponseData();
				if (login_response.getExeFlag() == 0) {
					alertDialog.dismiss();
					isExecuting = false;
					LoginActivity.this.showMessage(login_response.getMessage());
					return;
				}
				if (SystemConfig.readIsRememberUserName()) {
					SystemConfig.saveRememberedUserName(username);
				} else {
					usernameEt.setText("");
				}
				if (SystemConfig.readIsRememberPassword()) {
					SystemConfig.saveRememberedPassword(password);
				} else {
					passwordEt.setText("");
				}
				SystemConfig.setUserName(username);
				SystemConfig.setPassword(password);
				SystemConfig.setCookies(login_response.getCookies());

				// ///////////////////////////////
				WSOA_HttpGet_Request httpGetRequest = new WSOA_HttpGet_Request();
				httpGetRequest.setCookies(SystemConfig.getCookies());
				httpGetRequest.setUrl(login_response.getNextUrl());

				requests.clear();
				requests.put("request", httpGetRequest);
				response = SystemConfig.getService().Callservice(requests,
						"WSOA_HttpGet", WSOA_HttpGet_Response.class);

				if (!response.getExeFlag()) {
					alertDialog.dismiss();
					isExecuting = false;
					LoginActivity.this.showMessage(response.getMessage());
					return;
				}
				WSOA_HttpGet_Response httpGetResponse = (WSOA_HttpGet_Response) response
						.getResponseData();
				if (httpGetResponse.getExeFlag() == 0) {
					alertDialog.dismiss();
					isExecuting = false;
					LoginActivity.this
							.showMessage(httpGetResponse.getMessage());
					return;
				}
				// ///////////////////////////////
				// 异步下载通讯录
				new AsyncTask<String, Integer, ServiceResponse>() {

					protected ServiceResponse doInBackground(String... params) {
						WSOA_DownloadUnit_Request downloadUnitRequest = new WSOA_DownloadUnit_Request();
						downloadUnitRequest.setCookies(SystemConfig
								.getCookies());
						downloadUnitRequest.setUrl(params[0]);

						Map<String, BaseObject> requests = new HashMap<String, BaseObject>();
						requests.put("request", downloadUnitRequest);
						return SystemConfig.getService()
								.CallserviceOnMainThread(requests,
										"WSOA_DownloadUnit",
										WSOA_DownloadUnit_Response.class);
					}

					@Override
					protected void onPreExecute() {
					}

					@Override
					protected void onPostExecute(ServiceResponse response) {
						if (!response.getExeFlag()) {
							return;
						}
						WSOA_DownloadUnit_Response downloadUnitResponse = (WSOA_DownloadUnit_Response) response
								.getResponseData();
						if (downloadUnitResponse.getExeFlag() == 0) {
							return;
						}
						List<ContactInfo> contactList = new ArrayList<ContactInfo>();
						for (WSOA_Dept dept : downloadUnitResponse.getDepts()) {
							ContactInfo contactItem = new ContactInfo();
							contactItem.setFatherNodeId(0);
							contactItem.setName(dept.getDeptName());
							contactItem.setContactDescription("");
							contactItem.setType("D");

							addDeptContactInfo(dept, contactItem, contactList);
						}
						SystemConfig.setContactList(contactList);
					}

				}.execute(login_response.getDownloadFileInfo().get(0).getUrl());
				// ///////////////////////////////
				// 异步下载意见
				new AsyncTask<String, Integer, ServiceResponse>() {

					protected ServiceResponse doInBackground(String... params) {
						WSOA_DownloadOpinion_Request downloadOpinionRequest = new WSOA_DownloadOpinion_Request();
						downloadOpinionRequest.setCookies(SystemConfig
								.getCookies());
						downloadOpinionRequest.setUrl(params[0]);

						Map<String, BaseObject> requests = new HashMap<String, BaseObject>();
						requests.put("request", downloadOpinionRequest);
						return SystemConfig.getService()
								.CallserviceOnMainThread(requests,
										"WSOA_DownloadOpinion",
										WSOA_DownloadOpinion_Response.class);
					}

					@Override
					protected void onPreExecute() {
					}

					@Override
					protected void onPostExecute(ServiceResponse response) {
						if (!response.getExeFlag()) {
							return;
						}
						WSOA_DownloadOpinion_Response downloadOpinionResponse = (WSOA_DownloadOpinion_Response) response
								.getResponseData();
						if (downloadOpinionResponse.getExeFlag() == 0) {
							return;
						}
						SystemConfig.setOpinions(downloadOpinionResponse
								.getOpinions());
					}

				}.execute(login_response.getDownloadFileInfo().get(1).getUrl());
				// ///////////////////////////////
				Intent intent = new Intent();
				intent.setClass(LoginActivity.this, FuncPageActivity.class);

				intent.putExtra("page", httpGetResponse.getNextPage());
				intent.putExtra("url", login_response.getNextUrl());
				NewActivity(intent);
				alertDialog.dismiss();
				isExecuting = false;
			}
		}

	};

	public void addDeptContactInfo(WSOA_Dept deptNode, ContactInfo fatherNode,
			List<ContactInfo> nodeList) {
		if (deptNode == null) {
			return;
		}
		if (deptNode.getRoles() != null) {
			for (WSOA_Role role : deptNode.getRoles()) {
				ContactInfo contactItem = new ContactInfo();
				contactItem.setFatherNodeId(fatherNode.getNodeId());
				contactItem.setName(role.getRoleName());
				if (SystemConfig.stringIsNullOrEmpty(fatherNode
						.getContactDescription())) {
					contactItem.setContactDescription(fatherNode.getName());
				} else {
					contactItem.setContactDescription(fatherNode
							.getContactDescription()
							+ "\\"
							+ fatherNode.getName());
				}
				contactItem.setType("R");

				addRoleContactInfo(role, contactItem, nodeList);
			}
		}

		if (deptNode.getDepts() != null) {
			for (WSOA_Dept dept : deptNode.getDepts()) {
				ContactInfo contactItem = new ContactInfo();
				contactItem.setFatherNodeId(fatherNode.getNodeId());
				contactItem.setName(dept.getDeptName());
				if (SystemConfig.stringIsNullOrEmpty(fatherNode
						.getContactDescription())) {
					contactItem.setContactDescription(fatherNode.getName());
				}else{
					contactItem.setContactDescription(fatherNode
							.getContactDescription() + "\\" + fatherNode.getName());
				}
				contactItem.setType("D");

				addDeptContactInfo(dept, contactItem, nodeList);
			}
		}
	}

	public void addRoleContactInfo(WSOA_Role roleNode, ContactInfo fatherNode,
			List<ContactInfo> nodeList) {
		if (roleNode == null) {
			return;
		}
		if (roleNode.getUsers() != null) {
			for (WSOA_User user : roleNode.getUsers()) {
				ContactInfo contactItem = new ContactInfo();
				contactItem.setFatherNodeId(fatherNode.getNodeId());
				contactItem.setName(user.getUserName());
				contactItem.setUdf1(user.getSex());
				contactItem.setContactDescription(fatherNode
						.getContactDescription() + "\\" + fatherNode.getName());
				contactItem.setType("U");

				nodeList.add(contactItem);
			}
		}
	}
}
